package top.deepdesigner.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.deepdesigner.pojo.DtsRole;
import top.deepdesigner.service.DtsRoleService;

import java.util.*;

/**
 * Start up <br/>
 * Created with IntelliJ IDEA. <br/>
 * Project Name: shop_manage <br/>
 * Author: duanruiqing <br/>
 * DateTime: 2022/9/20 星期二 19:15:22 <br/>
 */
@Service
public class DtsRoleServiceImpl extends ServiceImpl<BaseMapper<DtsRole>, DtsRole> implements DtsRoleService {
  @Override
  public Set<String> getRoleIdByIds(Integer[] roleIds) {
    List<DtsRole> list = this.listByIds(Arrays.asList(roleIds));
    Set<String> strings = new HashSet<>();
    for (DtsRole dtsRole : list) {
      strings.add(dtsRole.getName());
    }
    return strings;
  }

  @Override
  public Long getRoleCount() {
    return this.count();
  }

  @Override
  public List<DtsRole> getRoleList(Integer page, Integer limit, String sort, String order) {
    return getRolePage(page, limit, sort, order).getRecords();
  }

  @Override
  public List<DtsRole> getRoleList() {
    return this.list();
  }

  @Override
  @Transactional
  public DtsRole createRole(String name, String desc) {
    //1、判断是否已经存在了当前角色
    List<DtsRole> list = this.list(new LambdaQueryWrapper<DtsRole>().eq(true, DtsRole::getName, name));
    if (list != null && list.size() != 0) {
      //2、如果存在返回空值
      return null;
    }
    //3、如果不存在，构建添加对象
    DtsRole dtsRole = new DtsRole();
    dtsRole.setName(name);
    dtsRole.setDesc(desc);
    dtsRole.setAddTime(new Date());
    this.save(dtsRole);
    return dtsRole;
  }

  @Override
  @Transactional
  public Boolean updateRole(DtsRole dtsRole) {
    UpdateWrapper<DtsRole> wrapper = new UpdateWrapper<>();
    wrapper.eq("id", dtsRole.getId());
    dtsRole.setUpdateTime(new Date());
    return this.update(dtsRole, wrapper);
  }

  @Override
  @Transactional
  public Boolean deleteRole(Integer id) {
    return this.remove(new LambdaQueryWrapper<DtsRole>().eq(true, DtsRole::getId, id));
  }

  //获取分页角色列表
  private Page<DtsRole> getRolePage(Integer page, Integer limit, String sort, String order) {
    QueryWrapper<DtsRole> wrapper = new QueryWrapper<>();
    wrapper.orderBy(true, "asc".equalsIgnoreCase(order), sort);
    Page<DtsRole> rolePage = new Page<>(page, limit);
    return this.page(rolePage, wrapper);
  }
}
